using ChikovMF.Application.Common.Interfaces;
using ChikovMF.Application.Features.Files.Shared;
using MediatR;

namespace ChikovMF.Application.Features.Files.AddFile;

public class AddFileCommandHandler : IRequestHandler<AddFileCommand, FileDto>
{
    public async Task<FileDto> Handle(AddFileCommand request, CancellationToken cancellationToken)
    {
        var fileDto = await _fileManager.SaveFile(request.FileStream, request.PathLocation, request.FileName, cancellationToken);

        _context.Files.Add(new Entities.File
        {
            Name = fileDto.Name,
            PathLocation = fileDto.PathLocation,
            UploadDate = DateTime.UtcNow,
            Url = fileDto.Url
        });

        await _context.SaveChangesAsync(cancellationToken);

        return fileDto;
    }
    
    private readonly IFileManager _fileManager;
    private readonly IChikovMFContext _context;
    public AddFileCommandHandler(IFileManager fileManager, IChikovMFContext context)
    {
        _fileManager = fileManager;
        _context = context;
    }
}